package com.zoro.barn.inner.service.documentsql.sql.service;

import com.zoro.barn.commons.tools.string.IDs;
import com.zoro.barn.inner.service.documentsql.sql.dao.SqlInfoMapper;
import com.zoro.barn.inner.service.documentsql.sql.dao.SqlUsageMapper;
import com.zoro.barn.inner.service.documentsql.sql.entity.SqlUsage;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhaoxingwu
 */
@Service
public class SqlInfoService {

    @Resource
    private SqlInfoMapper sqlInfoMapper;
    @Resource
    private SqlUsageMapper sqlUsageMapper;


    /**
     * calculate how many sql related to one product, and include project sql
     *
     * @param product product id
     * @return number
     */
    public Integer countByProduct(String product) {
        return this.sqlInfoMapper.countByProduct(product);
    }

    /**
     * calculate how many sql related to one project but don't include product sql
     *
     * @param project project id
     * @return number
     */
    public Integer countByProject(String project) {
        return this.sqlInfoMapper.countByProject(project);
    }

    @Transactional(rollbackFor = Exception.class)
    public void copySql(String fromProjectId, String toProjectId, String toProjectName) {

        // 1. 删除原有关联
        this.sqlUsageMapper.deleteByProject(toProjectId);
        // 2. 复制新关联
        List<SqlUsage> usages = this.sqlUsageMapper.getByProject(fromProjectId);
        if (CollectionUtils.isNotEmpty(usages)) {
            usages.forEach(v -> {
                v.setPid(IDs.uuid());
                v.setProjectId(toProjectId);
                v.setProjectName(toProjectName);
            });
            this.sqlUsageMapper.insertBatch(usages);
        }

    }

}
